<?php

/**
 * 赠送给某人/ 某些人 藏品
 * 后台操作
 */
class Given extends M_Controller
{
    private $success = 0;

    /**
     * 后台列表操作赠送藏品
     */
    public function beGiven()
    {
        $param = $this->input->post();
        try {
            if ((int)$param['id'] < 1) {
                throw new Exception('藏品信息缺失');
            }
            if (empty($param['uid'])) {
                throw new Exception('请选人员信息');
            } else {
                $userList = json_decode($param['uid']);
                if (!is_array($userList)) {
                    throw new Exception('用户格式错误');
                }
            }
            foreach ($userList as $user) {
                $this->db->trans_begin();
                $info = $this->models('favorite')->favoriteInfo(
                    $param['id'],
                    'id,catid,title,creator,title,thumb,price,nums,buy_nums,start_time,uid,author'
                );
                $nums = $this->getNums($info);
                $result = $this->favorite($info, ['nums' => $nums, 'uid' => $user]);
                $oid = $this->models('favorite')->addOrder($result, 'favorite');
                if ((int)$oid < 1) {
                    throw new Exception('入库失败,请稍后重试');
                }
                if (empty($this->models('favorite')->addOrderGood($oid, $result))) {
                    throw new Exception('订单商品添加失败', 1);
                }
                $payID = $this->models('system/pay')->create(
                    $user,
                    $result['info']['price'],
                    'favorite',
                    $oid,
                    '被赠送' . $result['info']['title'] . '此单免费'
                );
                // 将支付id 更新到订单
                $this->models('favorite')->operateOrder($oid, ['pay_id' => $payID]);
                // 确定购买之后将此物锁住, 支付完成后解锁 / 或取消支付 / 或订单超时解锁
                $this->models('favorite')->operateLock($result['info']['id'], 1);
                $this->models('favorite')->addQueue($user, $oid, 'favorite', $result['info']['id'], $result['nums']);
                $this->models('system/pay')->paySuccess('given', $payID);
                $this->db->trans_commit();
                $this->success++;
            }
            apiSuccess(1, '成功操作' . $this->success . '条');
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    // 可赠送用户的列表
    public function memberList()
    {
        $param = $this->input->get();
        // 搜索结果显示条数
        $pageSize = (int)$param['limit'] ?: 20;
        $page = max($param['page'], 1);
        $field = [
            ['fieldname' => 'username', 'name' => '账号'],
            ['fieldname' => 'name', 'name' => '昵称'],
            ['fieldname' => 'phone', 'name' => '手机号'],
        ];
        unset($param['d'], $param['s'], $param['c'], $param['page']);
        $query = $this->db->select('uid,username,name,phone,real_status');
        if (IS_POST) {
            $param = $this->input->post('data');
            if ($page['field']) {
                if ($param['field'] == 'name') {
                    $query->like('name', $param['keyword']);
                } else {
                    $query->where($param['field'], $param['keyword']);
                }
            }
        }
        $nums = $query->where('uid >', '2')->count_all_results('member', false);
        $list = $query->limit($pageSize, ($page - 1) * $pageSize)
            ->order_by('uid DESC')->get()->result_array();
        $this->template->assign(array(
            'list' => $list,
            'param' => $param,
            'field' => $field,
            'pages' => $this->get_pagination(dr_url('admin/favorite/given/memberList', $param), $nums, $pageSize),
        ));
        $this->template->display('people.html', 'admin');
    }

    /**
     * 购买藏品所需
     * @throws Exception
     */
    private function favorite($info, $field): array
    {
        if ($info['start_time'] > time()) {
            throw new Exception('尚未到达开启购买时间', 0);
        }
        if ($info['price'] < 0.01) {
            throw new Exception('价额设置错误,无法购买');
        }
        $nowNums = (int)$field['nums'];
        if ($nowNums < 1) {
            throw new Exception('商品编号错误');
        }
        if ($nowNums >= $info['nums']) {
            throw new Exception('已达购买最大限量', 0);
        }
        $lockStatus = $this->models('favorite')->snLockStatus($info['id'], $nowNums);
        if ($lockStatus) {
            throw new Exception('请稍等, 此编号正在购买');
        }
        if ($sn = $this->models('favorite')->getSn($info['id'])) {
            $sn = explode(',', $sn);
            if (in_array($nowNums, $sn)) {
                throw new Exception('此藏品已售出,请勿购买');
            }
        }
        $member = $this->models('member')->uidInfo(['uid' => $field['uid']], 'uid,name,username,team_code');
        return ['info' => $info, 'nums' => $nowNums, 'member' => $member];
    }

    // 取出可用的编号
    protected function getNums($info)
    {
        if (empty($info)) {
            return 0;
        }
        ### 此藏品对应视图中的内容
        $sn = $this->models('favorite')->getSn($info['id']);
        ###  此商品中含有锁的藏品编号
        $lockSn = $this->models('favorite')->getLockSn($info['id']);
        if ($lockSn) {
            $lockSn = array_column($lockSn, 'sn');
        }
        require_once WEBPATH . 'web/libraries/CreateSn.php';
        return (new CreateSn([
            'sn' => $sn,
            'buy_nums' => $info['buy_nums'],
            'max' => $info['nums'],
            'lock' => $lockSn ?: []
        ]))->getResult();
    }
}